export default class Ball {
  constructor(x, y, r = 10, isCueBall = false, color = '#ffffff', ballType = 'solid') {
    this.x = x;
    this.y = y;
    this.r = r;
    this.isCueBall = isCueBall;
    this.color = color;
    // 新增：球类型（solid 实心 / stripe 花球）
    this.ballType = ballType; // 'solid' | 'stripe'

    this.vx = 0;
    this.vy = 0;

    this.points = 1;
    this.isPocketed = false;
  }

  isMoving() {
    return Math.abs(this.vx) > 0.05 || Math.abs(this.vy) > 0.05;
  }

  pocket() {
    if (this.isPocketed) return;
    this.isPocketed = true;
    this.vx = 0;
    this.vy = 0;
  }

  reset(x, y) {
    this.isPocketed = false;
    this.x = x;
    this.y = y;
    this.vx = 0;
    this.vy = 0;
  }

  update(dt) {
    // 位移
    this.x += this.vx * dt * 60;
    this.y += this.vy * dt * 60;

    // 线性阻尼（模拟摩擦）
    const damping = 1.5; // 每秒阻尼系数
    const factor = Math.max(0, 1 - damping * dt);
    this.vx *= factor;
    this.vy *= factor;

    // 静止阈值
    if (Math.abs(this.vx) < 0.02) this.vx = 0;
    if (Math.abs(this.vy) < 0.02) this.vy = 0;
  }

  render(ctx) {
    ctx.save();
    ctx.beginPath();
    // 实心球：直接填充颜色；花球：白底+彩色带
    if (this.ballType === 'stripe' && !this.isCueBall) {
      // 白底
      ctx.fillStyle = '#ffffff';
      ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2);
      ctx.fill();

      // 在圆内裁剪后绘制一条彩色带
      ctx.beginPath();
      ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2);
      ctx.clip();
      ctx.fillStyle = this.color;
      ctx.fillRect(this.x - this.r, this.y - this.r * 0.6, this.r * 2, this.r * 1.2);
    } else {
      // 实心球或白球
      ctx.fillStyle = this.color;
      ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2);
      ctx.fill();
    }

    // 外圈描边
    ctx.strokeStyle = '#222';
    ctx.lineWidth = 1;
    ctx.beginPath();
    ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2);
    ctx.stroke();

    // 简易高光
    ctx.beginPath();
    ctx.fillStyle = 'rgba(255,255,255,0.25)';
    ctx.arc(this.x - this.r * 0.3, this.y - this.r * 0.3, this.r * 0.3, 0, Math.PI * 2);
    ctx.fill();

    ctx.restore();
  }
}